﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EasyStep.Business.Interfaces;
using WPF.TestEditor.Common.Interfaces;

namespace WPF.TestEditor.Controls
{

    public partial class BrowsersSelector : UserControlBase
    {

        public event EventHandler ExecuteTest;
        public event EventHandler StopTest;

        public BrowsersSelector():base()
        {
            InitializeComponent();
            this.DataContext = RegisteredBrowsers;
            _Selected = new IWebBrowserProxy[] { };
        }
        protected override void OnVisualParentChanged(DependencyObject oldParent)
        {
            base.OnVisualParentChanged(oldParent);
        }

        public IWebBrowserProxy[] RegisteredBrowsers
        {
            get
            {
                if (TestDataContext != null && TestDataContext.RegisteredBrowsers != null)
                    return TestDataContext.RegisteredBrowsers.Reverse().ToArray();
                else
                    return null;
            }
        }
        public IWebBrowserProxy[] _Selected;
        public IWebBrowserProxy[] Selected
        {
            get
            {
                if (_Selected == null || _Selected.Length == 0) _Selected = GetSelected().ToArray();
                return _Selected;
            }
            set
            {
                SetSelected(value);
            }
        }

        private void ttbExecuteTest_Click(object sender, RoutedEventArgs e)
        {
            if (TestDataContext != null) TestDataContext.Log.Debug("Execute Event : Run Test, browser selector control");
            ExecuteTest.Invoke(sender,e);

        }
        
        private void BitmapImage_DownloadFailed(object sender, ExceptionEventArgs e)
        {
            if (TestDataContext != null)
                TestDataContext.Log.Error("BitmapImage.Can't load browser thumbnail image:", e.ErrorException);
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            if (TestDataContext != null)
                TestDataContext.Log.Error("ImageFailed.Can't load browser thumbnail image:", e.ErrorException);
            e.Handled = true;
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            var c = sender as CheckBox;
            var t = c.Tag as IWebBrowserProxy;
            if (TestDataContext != null) TestDataContext.Log.Debug("Refresh Selected browsers, browser selector control");
            _Selected = null;
        }
        
        public IEnumerable<IWebBrowserProxy> GetSelected(DependencyObject parent=null)
        {
            if (parent == null) parent = this.BrowsersList;
            var chCount = VisualTreeHelper.GetChildrenCount(parent);
            var selected=new List<IWebBrowserProxy>();
            for (int i = 0; i < chCount; i++)
            {
                var c = VisualTreeHelper.GetChild(parent, i);
                if ((c is CheckBox) && (c as CheckBox).IsChecked.Value)
                {
                    yield return (c as CheckBox).Tag as IWebBrowserProxy;
                }
                else
                    foreach (var cr in GetSelected(c))
                        yield return cr;
            }
        }

        public void  SetSelected(IEnumerable<IWebBrowserProxy> data, DependencyObject parent = null)
        {
            if (TestDataContext != null) TestDataContext.Log.Debug("Reset checkboxes =>Selected browsers, browser selector control");
            if (parent == null) parent = this.BrowsersList;
            var chCount = VisualTreeHelper.GetChildrenCount(parent);
            var selected = new List<IWebBrowserProxy>();
            for (int i = 0; i < chCount; i++)
            {
                var c = VisualTreeHelper.GetChild(parent, i);
                if ((c is CheckBox))
                {
                    var cc = c as CheckBox;
                    var cname = cc == null ? null : (cc.Tag as IWebBrowserProxy).Name;
                    cc.IsChecked = !string.IsNullOrEmpty(cname) && data.Where(itm => itm.Name.Equals(cname)).Any();
                }
                else
                    SetSelected(data, c);
            }
        }

        private void Image_MouseUp(object sender, MouseButtonEventArgs e)
        {
            var p = VisualTreeHelper.GetParent(sender as DependencyObject);
            if (p == null) return;
            var chCount = VisualTreeHelper.GetChildrenCount(p);
            for (var i = 0; i < chCount; i++)
            {
                var c = VisualTreeHelper.GetChild(p, i);
                if (c is CheckBox)
                {
                    var cc = c as CheckBox;
                    cc.IsChecked = !cc.IsChecked;
                }
            }
        }
        private void ttbStopTest_Click(object sender, RoutedEventArgs e)
        {
            if (TestDataContext != null) TestDataContext.Log.Debug("Execute Event : Stop button has been clicked");
            StopTest.Invoke(sender, e);
        }

        public void SetState(bool isWorking)
        {
            ttbStopTest.Visibility = isWorking ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            ttbExecuteTest.Visibility = !isWorking ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }
    }


    
}
